<template>
  <div id="Supplier">
    <section class="jarallax py-5">
      <img src="@/assets/images/banner-1.jpg" class="jarallax-img">
      <div class="hero-content py-0 py-md-5">
        <div class="container-lg d-flex flex-column d-md-block align-items-center">
          <nav class="breadcrumb">
            <a class="breadcrumb-item nav-link" href="/Organic/home">主页</a>
            <a class="breadcrumb-item nav-link" href="/Organic/supplier">页面</a>
            <span class="breadcrumb-item active" aria-current="page">供应商</span>
          </nav>
          <h1>{{title}}</h1>
        </div>
      </div>
    </section>

    <section class="py-5">
      <div class="container-lg">
        <div class="row g-5">
          <el-card v-if="supplierTag === 'S001-1'" class="box-card" style="width: 100%;height: 100%">
            <div slot="header">
              <el-row :gutter="20">
                <el-col :span="20">
                  <el-upload
                      class="avatar-uploader"
                      ref="upload"
                      action="#"
                      :auto-upload="false"
                      :show-file-list="false"
                      @click.native.prevent> <!-- 阻止默认点击行为 -->
                    <div class="grid-content bg-purple">
                      <el-avatar slot="trigger" :size="90" :src="img" @error="errorHandler" @click.native="handleAvatarClick" style="margin: 0 auto">
                        <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
                      </el-avatar>
                    </div>
                  </el-upload>
                  <input type="file" ref="fileInput" style="display: none" @change="handleFileChange">
                </el-col>
              </el-row>
            </div>
            <el-form ref="form" :model="supplierForm" :rules="rules" label-width="100px">
              <el-form-item label="公司名称" prop="companyName">
                <el-input v-model="supplierForm.companyName"></el-input>
              </el-form-item>
              <el-form-item label="法定代表人" prop="name">
                <el-input v-model="supplierForm.name"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="supplierForm.phone"></el-input>
              </el-form-item>
              <el-form-item label="地址" prop="Addr">
                <el-input v-model="supplierForm.Addr"></el-input>
                <el-button type="primary" @click="handleAddress">选择地址</el-button>
              </el-form-item>

              <el-form-item>
                <!--                <el-button type="primary" @click="updateUser=true">取消</el-button>-->
                <el-button type="primary" @click="submitUpload">申请</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <el-card v-if="supplierTag === 'S001-2'" class="box-card" style="width: 100%;height: 100%">
            <span><i class="el-icon-loading"></i>审核中...</span>
          </el-card>
          <el-card v-if="supplierTag === 'S001-3'" class="box-card" style="width: 100%;height: 100%">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="商户详情" name="first">
                <el-card v-if="updateSupplier === false" class="box-card" style="width: 100%;height: 100%">
                  <div slot="header">
                    <el-row :gutter="20">
                      <el-col :span="20">
                        <div class="grid-content bg-purple">
                          <el-avatar :size="90" :src="'http://localhost:90'+supplier.licenseLink" @error="errorHandler"  style="margin: 0 auto">
                            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
                          </el-avatar>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                  <el-descriptions class="margin-top" title="我的信息" :column="2"  border>
                    <template slot="extra">
                      <el-button type="primary" size="small" @click="updateSupplier = true">更新</el-button>
                    </template>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        代表人姓名
                      </template>
                      {{supplier.name}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user-solid"></i>
                        公司名称
                      </template>
                      {{supplier.companyName}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        手机号
                      </template>
                      {{supplier.phone}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        余额
                      </template>
                      {{supplier.balance}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-location-outline"></i>
                        生活地址
                      </template>
                      {{supplier.address}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-office-building"></i>
                        详细地址
                      </template>
                      {{supplier.detailAddress}}
                    </el-descriptions-item>
                  </el-descriptions>
                </el-card>
                <el-card v-if="updateSupplier === true" class="box-card" style="width: 100%;height: 100%">
                  <div slot="header">
                    <el-row :gutter="20">
                      <el-col :span="20">
                        <el-upload
                            class="avatar-uploader"
                            ref="upload"
                            action="#"
                            :auto-upload="false"
                            :show-file-list="false"
                            @click.native.prevent> <!-- 阻止默认点击行为 -->
                          <div class="grid-content bg-purple">
                            <el-avatar slot="trigger" :size="90" :src="img" @error="errorHandler" @click.native="handleAvatarClick" style="margin: 0 auto">
                              <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
                            </el-avatar>
                          </div>
                        </el-upload>
                        <input type="file" ref="fileInput" style="display: none" @change="handleFileChange">
                      </el-col>
                    </el-row>
                  </div>
                  <el-form ref="form" :model="supplierForm" :rules="rules" label-width="100px">
                    <el-form-item label="公司名称" prop="companyName">
                      <el-input v-model="supplierForm.companyName"></el-input>
                    </el-form-item>
                    <el-form-item label="法定代表人" prop="name">
                      <el-input v-model="supplierForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                      <el-input v-model="supplierForm.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="地址" prop="Addr">
                      <el-input v-model="supplierForm.Addr"></el-input>
                      <el-button type="primary" @click="handleAddress">选择地址</el-button>
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="updateSupplier=false">取消</el-button>
                      <el-button type="primary" @click="submitUpload">更新</el-button>
                      <el-button @click="resetForm">重置</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-tab-pane>
              <el-tab-pane label="商品叫价" name="second">
                <el-row>
                  <el-col :span="22">
                    <el-form :inline="true" :model="searchData" class="demo-form-inline">
                      <el-form-item label="类别:">
                        <el-select v-model="searchData.type" clearable placeholder="请选择">
                          <el-option
                              v-for="item in types"
                              :key="item.typeId"
                              :label="item.typeName"
                              :value="item.typeId" >
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="名称:">
                        <el-input v-model="searchData.keywordInput" clearable placeholder="名称："></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="onSubmit">查询</el-button>
                      </el-form-item>
                    </el-form>
                  </el-col>
<!--                  <el-col :span="2">-->
<!--                    <el-button type="primary" @click="dialogFormVisible = true" round>添加</el-button>-->
<!--                  </el-col>-->
                </el-row>
                <el-table :data="tableData" border style="width: 100%">
                  <el-table-column fixed prop="name" label="商品图片" width="250" align="center">
                    <template slot-scope="scope">
                      <img :src="'/img' + scope.row.imgLink" alt="商品图片" style="width: 50px; height: 50px;">
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="商品名称" width="250" align="center" ></el-table-column>
                  <el-table-column prop="typeId" label="类型" width="120" align="center">
                    <template slot-scope="scope">
                      {{conversionType(scope.row.typeId)}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="市场价格" width="120" align="center"></el-table-column>
                  <el-table-column prop="unit" label="单位" width="120" align="center"></el-table-column>
                  <el-table-column fixed="right" label="操作" align="center">
                    <template slot-scope="scope">
                      <el-button  @click="askingPrice(scope.row.productId)" type="primary" size="small">我有货</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
                <el-dialog title="我的叫价" :visible.sync="dialogFormVisible" width="30%" @close="dialogClose">
                  <el-descriptions class="margin-top"  :column="1" size="medium" border>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        商品名称
                      </template>
                      {{product.name}}
                    </el-descriptions-item>
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        市场价格
                      </template>
                      {{product.price}}
                    </el-descriptions-item>
                    <!-- 输入叫价-->
                    <el-descriptions-item>
                      <template slot="label">
                        <i class="el-icon-user"></i>
                        我的叫价
                      </template>
                      <el-form :rules="askingPriceRules" ref="askingPriceRules" :model="askingPriceFrom" label-width="80px" class="demo-ruleForm">
                        <el-form-item label="叫价" prop="askingPrice">
                          <el-input v-model="askingPriceFrom.askingPrice" placeholder="请输入你的叫价"></el-input>
                        </el-form-item>
                      </el-form>
                    </el-descriptions-item>
                  </el-descriptions>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false" >取 消</el-button>
                    <el-button type="primary" @click="askingPriceSubmit('askingPriceRules')">确 定</el-button>
                  </div>
                </el-dialog>
              </el-tab-pane>
              <el-tab-pane label="我的叫价" name="third">
                <MyAskingPrice ref="myAskingPrice"/>
              </el-tab-pane>
              <el-tab-pane label="订单管理" name="fourth">
                <SupplierOrder />
              </el-tab-pane>
            </el-tabs>
          </el-card>
          <el-dialog title="地址" :visible.sync="showAddressDialog" width="80%" >
            <div style="height: 450px">
              <Map ref="map" @updateLocation="updateLocation" />
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showAddressDialog = false">取 消</el-button>
              <el-button type="primary" @click="setMapAddrToAddress">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import Map from "@/components/OrganicBody/AMapSearch.vue";
import {right} from "core-js/internals/array-reduce";
import MyAskingPrice from "@/components/OrganicBody/Supplier-children/MyAskingPrice.vue";
import SupplierOrder from "@/components/OrganicBody/Supplier-children/SupplierOrder.vue";

export default {
  name: 'SupplierBody',
  components: {
    SupplierOrder,
    MyAskingPrice,
    Map
  },
  props: {},
  data () {
    return {
      title: '商户',
      updateSupplier:false,
      user: {},
      supplierTag: "",
      supplier:{},
      img: '',
      supplierForm: {
        companyName:'',
        name:'',
        phone:'',
        address:'',
        detailAddress:'',
        Addr:'',
      },
      rules: {
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          { min: 2, max: 30, message: '公司名称长度应在2到30个字符之间', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入法定代表人姓名', trigger: 'blur' },
          { min: 2, max: 30, message: '法定代表人姓名长度应在2到30个字符之间', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 2, max: 30, message: '地址长度应在2到30个字符之间', trigger: 'blur' }
        ],
      },
      showAddressDialog: false,
      MapAddr: '',
      fileList: [],
      activeName: 'first',

      searchData: {
        keywordInput: '',
        type: ''
      },
      types: [],
      Types: [],
      tableData: [],
      currentPage : 1,
      total : 0,
      pageSize : 5,
      product:{},
      dialogFormVisible : false,
      askingPriceFrom:{
        askingPrice: ''
      },
      askingPriceRules: {
        askingPrice: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { pattern: /^[1-9]\d*(\.\d+)?$/, message: '请输入有效的价格', trigger: 'blur' }
        ]
      },
    }
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    right,
    intUser() {
      this.user = this.$store.state.user;
      // eslint-disable-next-line no-empty
      if (this.user.supplierTag === "S001-3") {
        this.supplier = this.$store.state.supplier
        this.supplierTag = "S001-3";
        this.title = "供应商详情";
        // eslint-disable-next-line no-empty
      } else if (this.user.supplierTag === "S001-2") {
        this.supplierTag = "S001-2";
        this.title = "审核中";
      } else {
        this.supplierTag = "S001-1";
        this.title = "申请成为供应商";
      }
    },
    errorHandler() {
      return true;
    },
    handleAvatarClick() {
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt500KB = file.size / 1024 < 500;

        if (!isJPGOrPNG) {
          this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
          return;
        }
        if (!isLt500KB) {
          this.$message.error('上传图片大小不能超过 500KB!');
          return;
        }

        this.img = URL.createObjectURL(file);
        this.fileList = [{ name: file.name, url: this.img, raw: file }];
      }
    },
    submitUpload() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.fileList.length === 0) {
            this.$message.error('请上传头像图片');
            return;
          }

          let formData = new FormData();
          formData.append('consumerId', this.user.consumerId);
          formData.append('companyName', this.supplierForm.companyName);
          formData.append('name', this.supplierForm.name);
          formData.append('phone', this.supplierForm.phone);
          formData.append('address', this.supplierForm.address);
          formData.append('detailAddress', this.supplierForm.detailAddress);
          formData.append('lng', this.MapAddr.lon);
          formData.append('lat', this.MapAddr.lat);
          if(this.supplier.supplierId !== null && this.supplier.supplierId !== undefined){
            formData.append('supplierId', this.supplier.supplierId);
          }

          this.fileList.forEach(file => {
            formData.append('files', file.raw);
          });

          this.$axios.post('http://localhost:8090/supplier/saveSupplier', formData).then(({ data }) => {
            if (data !== null && data !== undefined) {
              this.$notify({
                title: '正在申请',
                message: '正在申请成供应商！' + data.name,
                type: 'success'
              });
              this.supplierTag = "S001-2";
              this.title = "审核中";
            }
            console.log(data);
          }).catch(error => {
            this.$notify({
              title: '申请失败',
              message: '申请失败，请稍后重试',
              type: 'warning'
            });
            console.error(error);
          });
        } else {
          // this.$message.error('请检查表单输入是否正确');
          this.$notify({
            title: '更新失败',
            message: '请检查表单输入是否正确',
            type: 'warning'
          });
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
      this.img = '';
      this.fileList = [];
    },
    handleAddress() {
      this.showAddressDialog = true;
    },
    setMapAddrToAddress() {
      let address = this.MapAddr.province + '-' + this.MapAddr.city + '-' + this.MapAddr.district;
      let detailAddress = this.MapAddr.orgAddr;
      this.supplierForm.address = address;
      this.supplierForm.detailAddress = detailAddress;
      this.supplierForm.Addr = address + '-' + detailAddress+this.supplierForm.shopName;
      this.showAddressDialog = false;
    },
    // 点击地图后得到位置信息
    updateLocation(Addr) {
      this.MapAddr = Addr;
      console.log(this.MapAddr);
    },
    handleClick(tab) {
      if(tab.index==="1"){
        this.InitializeThePage();
      }else if (tab.index==="2"){
        this.InitMyAskingPrice();
      }
    },

    handleSizeChange(val) {//页大小改变时
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.InitializeThePage();
    },
    handleCurrentChange(val) {//页码发生改变时
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.InitializeThePage();
    },
    onSubmit(){
      this.InitializeThePage();
    },
    InitializeThePage(){
      Object.assign(this.searchData, {"currentPage": this.currentPage, "pageSize": this.pageSize})
      this.$axios.post("http://localhost:8090/product/getProducts", this.searchData).then(({ data }) => {
        this.tableData = data.records;
        this.total = data.total;
        console.log(data);
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '初始化失败!'
        });
      })
    },
    initialTypeSelect: function () {
      this.$axios.get("http://localhost:8090/product-type/getAllProductType?level="+2).then(({ data }) => {
        this.types = data;
      })
      this.$axios.get("http://localhost:8090/product-type/getAllProductType").then(({ data }) => {
        this.Types = data;
      })
    },
    conversionType(typeId){
      let type = typeId.split('-')[1]
      for(let i=0;i<this.Types.length;i++){
        if(this.Types[i].typeId==type){
          return this.Types[i].typeName
        }
      }
    },
    checkAskingPrice(productId){
      let b = true;
      let formData = new FormData();
      formData.append('supplierId', this.supplier.supplierId);
      formData.append('productId', productId);
      this.$axios.post("http://localhost:8090/supplier-product/getSupplierProductBySupplierIdAndProductId", formData).then(({ data }) => {
        if (data !== null && data !== undefined && data!==''){
          b = false
          console.log(data)
        }else {
          b = true
        }
      })
      return b
    },
    askingPrice(productId){
      let formData = new FormData();
      formData.append('supplierId', this.supplier.supplierId);
      formData.append('productId', productId);
      this.$axios.post("http://localhost:8090/supplier-product/getSupplierProductBySupplierIdAndProductId", formData).then(({ data }) => {
        if (data !== null && data !== undefined && data!==''){
          this.$notify({
            title: '叫价',
            message: '叫价失败！你已经叫价过该商品！',
            type: 'error'
          });
        }else {
          this.$axios.get("http://localhost:8090/product/getProductById?productId="+productId).then(({ data }) => {
            this.product = data;
            this.dialogFormVisible = true
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '叫价失败!'
            });
          })
        }
      })

    },
    dialogClose(){
      this.dialogFormVisible = false
    },
    askingPriceSubmit(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append('supplierId', this.supplier.supplierId);
          formData.append('productId', this.product.productId);
          formData.append('price', this.askingPriceFrom.askingPrice);
          this.$axios.post("http://localhost:8090/supplier-product/saveSupplierProduct", formData).then(({ data }) => {
            // eslint-disable-next-line no-empty
            if(data){
              this.$notify({
                title: '叫价成功',
                message: '叫价成功！',
                type: 'success'
              });
              this.dialogFormVisible = false
              // eslint-disable-next-line no-empty
            }else {
              this.$notify({
                title: '叫价失败',
                message: '叫价失败！',
                type: 'warning'
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    InitMyAskingPrice(){
      this.$refs.myAskingPrice.InitializeThePage();
    },

  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.intUser()
    this.initialTypeSelect()
  },
  // 生命周期 - 创建之前
  beforeCreate () {},
  // 生命周期 - 挂载之前
  beforeMount () {},
  // 生命周期 - 更新之前
  beforeUpdate () {},
  // 生命周期 - 更新之后
  updated () {},
  // 生命周期 - 销毁之前
  beforeDestroy () {},
  // 生命周期 - 销毁完成
  destroyed () {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated () {}
}
</script>

<style scoped>

</style>
